package canglang.scan.login.action;

import canglang.scan.core.base.action.BaseAction;
import canglang.scan.core.base.properties.AppDefaultProperty;
import canglang.scan.core.base.util.DateUtil;
import canglang.scan.user.model.UserModel;
import canglang.scan.user.service.UserManager;

public class LoginAction extends BaseAction {

    private static final long serialVersionUID = 5724884389427207299L;

    private String USER="user";

    private String ADMIN="admin";

    private UserManager userManager;

    private UserModel userModel;

    public UserManager getUserManager() {
        return userManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public UserModel getUserModel() {
        return userModel;
    }

    public void setUserModel(UserModel userModel) {
        this.userModel = userModel;
    }

    public String login(){
        UserModel user = userManager.getUser(userModel.getUserId());
        if(user==null){
            this.addActionError(AppDefaultProperty.getProperty("label.user.does.not.exist"));
            return INPUT;
        }
        if(!user.getUserPassword().equals(userModel.getUserPassword())){
            this.addActionError(AppDefaultProperty.getProperty("label.password.wrong"));
            return INPUT;
        }
        this.getSession().setAttribute(USER, user);
        if(user.getUserRole().equalsIgnoreCase("A")){
            return ADMIN;
        }else{
            return USER;
        }
    }

    public String changePassword(){
        UserModel user = userManager.getUser(userModel.getUserId());
        if(user!=null){
            if(user.getUserPassword().equals(userModel.getUserPassword())){
                user.setUserPassword(userModel.getNewPassword());
                user.setUpdateDt(DateUtil.getDate());
                userManager.saveUser(user);
            }else{
                this.addActionError(AppDefaultProperty.getProperty("label.password.wrong"));
                return INPUT;
            }
        }else{
            this.addActionError(AppDefaultProperty.getProperty("label.user.does.not.exist"));
            return INPUT;
        }
        this.saveMessage(AppDefaultProperty.getProperty("label.password.change.successful"));
        return SUCCESS;
    }

}
